import sys
import os
import subprocess
import signal
import json


def qad_client_script2018(program_name, in_path, trace_id):
    data = {

    }

    os.environ['DLC'] = r'/db/dlc'

    p = subprocess.Popen(["stty", "intr", "^c"])
    p.wait()
    p = subprocess.Popen(". %s; echo LD_LIBRARY_PATH=$LD_LIBRARY_PATH; echo SHLIB_PATH=$SHLIB_PATH; echo "
                         "LIBPATH=$LIBPATH; echo PROLIBPATH=$PROLIBPATH" % os.path.join(r'/db/dlc', 'bin',
                                                                                        'slib_env'),
                         stdout=subprocess.PIPE, shell=True)
    output = p.communicate()[0]
    environ = dict(line.split("=", 1) for line in output.decode().splitlines())
    os.environ.update(environ)

    os.environ['PATH'] = os.path.join(r'/db/dlc', 'bin') + ':' + os.environ['PATH']

    os.environ['PROMSGS'] = os.path.join(r"/db/dlc", "promsgs")
    os.environ['PROTERMCAP'] = os.path.join(r"/db/dlc", "protermcap")
    os.environ['PS1'] = str(os.getpid())
    os.environ[
        'PROPATH'] = r'/apps/ee2018/config,/apps/ee2018/build/catalog/packages/qracore/3/0/3/1/qad.qra.core/bin' \
                     r'/qracore.pl,/apps/ee2018/dist/mfg-customizations,/apps/ee2018/dist/fin/proxypatch,' \
                     r'/apps/ee2018/dist/pro/com/mfgpro,/apps/ee2018/dist/qxtadpt,/apps/ee2018/dist/mfg,' \
                     r'/apps/ee2018/dist/mfg/us,/apps/ee2018/dist/mfg/us/xx,/apps/ee2018/dist/mfg/us/bbi,' \
                     r'/apps/ee2018/build/catalog/packages/fin-bin64-proxy/2018/0/0/3/proxy.pl,/apps/ee2018/dist/pro,' \
                     r'.,/apps/ee2018/build/catalog/packages/qra-oe11/1/1/174/0/lib/qra.pl'
    os.environ['APPDIR'] = r'/apps/ee2018'

    # if len(sys.argv) > 1:
    #    codepage = sys.argv[1]
    # else:
    #    codepage = 'cp936'
    startup_params = ''

    codepage = 'cp936'

    # if codepage == 'utf-8':
    #    startup_params = '-ucc -utf8intatchar ' + startup_params

    # if 'TERM' not in os.environ:
    #    os.environ['TERM'] = raw_input("Please enter your terminal type: ")
    #

    program = os.path.expandvars(
        r'com/qad/qra/core/ClientBootstrap.p -param startup=' + program_name + ',logfile=/apps/ee2018/build/logs'
                                                                               '/client/session-chui-${USER}.log')

    params = [os.path.join(r"/db/dlc", "bin", "_progres"), "-pf",
              r'/apps/ee2018/build/work/generated/application.pf'] + startup_params.split() + ["-cpinternal", codepage,
                                                                                               "-cpstream", codepage,
                                                                                               "-p"] + program.split()
    print(params)
    pcwd = os.path.abspath(os.path.expandvars(os.path.expanduser(r'/home/mfg')))
    p = subprocess.Popen(params, cwd=pcwd)

    # signal.signal(signal.SIGINT, signal.SIG_IGN)
    p.wait()
    in_path = in_path.replace('cim/', 'out/')
    with open(in_path + trace_id + '.run.log', 'r', encoding='cp936') as runlog:
        for line in runlog:
            # print(line)
            if line.find("**") >= 0 or line.find("error") >= 0:
                data['error_msg'] = line
                data['status'] = 'Failed'
                return data, False

    try:
        with open(in_path + trace_id + '.run.out.json', 'r', encoding='utf-8') as runlog1:
            # print(in_path + trace_id + '.run.out.json')
            data = json.load(runlog1)
            # print(data)
        return data, True
    except FileNotFoundError:
        return data, False
